package com.tsfyun.scm.declarechannel.service.impl;

import cn.hutool.http.HttpRequest;
import com.tsfyun.scm.declarechannel.entity.CusConfig;
import com.tsfyun.scm.declarechannel.mapper.CusConfigMapper;
import com.tsfyun.scm.declarechannel.service.ICusConfigService;
import com.tsfyun.scm.declarechannel.util.GrabSinglewindow;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.HttpPost;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class CusConfigServiceImpl implements ICusConfigService {

    @Autowired
    private CusConfigMapper cusConfigMapper;

    private CusConfigServiceImpl(){
        System.setProperty("webdriver.chrome.driver", "D:/chromedriver.exe");
    }

    @Override
    public void startUpdateCookie() {
        WebDriver driver = null;
        try{
            log.info(String.format("开始尝试自动登录"));
            System.setProperty("webdriver.chrome.driver", "D:/chromedriver.exe");
            driver = new ChromeDriver();
            //driver.manage().window().setSize(new Dimension(0,0));
            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
            driver.navigate().to("http://app.singlewindow.cn/cas/login?_local_card_flag=1&service=http%3A%2F%2Fapp.singlewindow.cn%2Fcas%2Fjump.jsp%3FtoUrl%3DaHR0cDovL2FwcC5zaW5nbGV3aW5kb3cuY24vY2FzL29hdXRoMi4wL2F1dGhvcml6ZT9jbGllbnRfaWQ9c3owMDAwMDAwMFZlNFM5SjAxNCZyZXNwb25zZV90eXBlPWNvZGUmcmVkaXJlY3RfdXJpPWh0dHAlM0ElMkYlMkZzei5zaW5nbGV3aW5kb3cuY24lMkZkeWNrJTJGT0F1dGhMb2dpbkNvbnRyb2xsZXI%3D&configInfoB64=JmNvbG9yQTE9ZDFlNGZiJmNvbG9yQTI9NjYsIDEyNCwgMTkzLCAwLjg%3D&_local_login_flag=1&logoutFlag=1&localServerUrl=http%3A%2F%2Fsz.singlewindow.cn%2Fdyck&localDeliverParaUrl=%2Fdeliver_para.jsp");
            Thread.sleep(2000);
            WebElement passwordElement = driver.findElement(By.id("password"));
            passwordElement.sendKeys("88888888");
            WebElement loginbutton = driver.findElement(By.id("loginbutton"));
            loginbutton.click();
            Thread.sleep(4000);
            driver.navigate().to("http://sz.singlewindow.cn/dyck/swProxy/deskserver/sw/deskIndex?menu_id=dec001");
            Thread.sleep(3000);
            Set<Cookie> cookies = driver.manage().getCookies();
            List<String> cookieList = new ArrayList<>();
            cookies.stream().forEach(cookie -> {
                cookieList.add(String.format("%s=%s",cookie.getName(),cookie.getValue()));
            });
            String cookieStr = String.join("; ",cookieList);
            log.info(String.format("成功获取到COOKIE【%s】",cookieStr));
            if(cookieStr.indexOf("!Proxy!route1plat")>=0&&cookieStr.indexOf("!Proxy!JSESSIONID")>=0){
                CusConfig cusConfig = new CusConfig();
                cusConfig.setId("cookie");
                cusConfig.setVal(cookieStr);
                cusConfig.setDateUpdated(LocalDateTime.now());
                cusConfigMapper.saveExistenceUpdate(cusConfig);
                log.info("COOKIE有效");
                //发送至服务器
                new Thread(()->{
                    log.info("开始发送至服务器........");
                    String res = HttpRequest.post("https://www.xxxx.com/base/support/cacheSwToken").addHeaders(new HashMap<String, String>(){{
                        put("accept-salt","qwert12345");
                    }}).form(new HashMap<String, Object>(){{
                        put("token",cookieStr);
                    }}).execute().body();
                    log.info("服务器返回：");
                    log.info(res);
                }).start();
            }else{
                log.info("COOKIE无效");
            }
        }catch (Exception e){
            log.info("自动登录失败：",e);
        }finally {
            driver.quit();
        }
    }

    // 是否启动
    private static Boolean isStart = false;

    @Override
    public void receiver(String message) {
        if(!isStart){
            isStart = true;
            startUpdateCookie();
            isStart = false;
        }else{
            log.info("自动登录程序运行中");
        }
    }
}
